//
//  SDPaientInfoViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/7/24.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDPaientInfoViewController.h"
#import "SDPhotoDetailInfoViewController.h"
#import "SDPaientInfoMgr.h"
#import "SDTabBarController.h"
#import "SDPhotoInfo.h"
#import "VPTabBar.h"
#import "SDPhotoCollectionCell.h"
#import "AliyunOSSManager.h"
#import "SDPaientInfoLTView.h"
#import "SDPaientEditorViewController.h"
#import "SDNavigationController.h"
#import "SDPaientPhotoData.h"

#define kHeaderViewHeight 173

static NSString * const collectionCellIdentifier = @"UICollectionViewCell";

@interface SDPaientInfoViewController()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,VPTabBarDelegate,SDBaseDataDelegate>
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong) NSArray *itemsArray;
@property(nonatomic, strong) NSMutableArray* selectedItemsArray;

@property(nonatomic,strong)NSArray* photoList;
@property(nonatomic,strong)VPTabBar* bottomBar;
@property(nonatomic,assign)BOOL editable;
@property(nonatomic,assign)float photoViewWidth;

@property(nonatomic, strong) SDAvatarView *avatarView;
@property(nonatomic, strong) SDPaientInfoLTView* idTextView;
@property(nonatomic, strong) SDPaientInfoLTView* nameTextView;
@property(nonatomic, strong) SDPaientInfoLTView* genderTextView;
@property(nonatomic, strong) SDPaientInfoLTView* birthdayTextView;

@property(nonatomic,strong)SDPaientPhotoData* photoData;
@end

@implementation SDPaientInfoViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initData];
    [self initViews];
    
    if (_selectedItemsArray == nil) {
        _selectedItemsArray = [NSMutableArray arrayWithCapacity:1];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self refreshProfileInfoView];
}

-(void)initViews
{
    _photoViewWidth = ((kScreenWidth + 1) - 4) / 4;
    BOOL barHidden = [self navigationBarHidden];
    if (!barHidden && self.navBar != nil)
    {
        [self.navBar setTitle:[NSString stringWithFormat:@"%@的照片",_paientItem.name]];
        UIImage* addImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_back.png");
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) image:addImg];
        //[self.navBar customNaviRightButton:self action:@selector(onCancel:) title:@"取消"];
    }
    
    
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:autoRectTableViewHaveBar(!barHidden) collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
    [self.collectionView registerClass:[SDPhotoCollectionCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    
    UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    collectionViewLayout.headerReferenceSize = CGSizeMake(kScreenWidth, kHeaderViewHeight);
    
    [self.view addSubview:self.collectionView];
}

-(UIView*)bottomBar
{
    VPTBarBtn* one = [[VPTBarBtn alloc] init];
    one.normalImg = [UIImage imageNamed:@"gallery_btn_sync.png"];
    one.selectImg = [UIImage imageNamed:@"gallery_btn_sync.png"];
    one.normalColor = [UIColor colorWithRGB:0x747F8B];
    one.selectColor = [UIColor colorWithRGB:0x747F8B];
    one.rightTitle = @"同步";
    
    VPTBarBtn* two = [[VPTBarBtn alloc] init];
    two.normalImg = [UIImage imageNamed:@"gallery_btn_delete.png"];
    two.selectImg = [UIImage imageNamed:@"gallery_btn_delete.png"];
    two.normalColor = [UIColor colorWithRGB:0x747F8B];
    two.selectColor = [UIColor colorWithRGB:0x747F8B];
    two.rightTitle = @"删除";
    
    
    _bottomBar = [[VPTabBar alloc] initWithPosY:0 btnList:[NSArray arrayWithObjects:one, two, nil]];
    _bottomBar.mydelegate = self;
    _bottomBar.backgroundColor = [UIColor colorWithRGB:0xffffff];
    [_bottomBar initMyContent];
    [one setIsSelectedMine:NO];
    [two setIsSelectedMine:NO];
    //    UIView* bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, MainTabBar_H)];
    //    bottomBar.backgroundColor = [UIColor redColor];
    return _bottomBar;
}

-(void)initData
{
    _photoData = [[SDPaientPhotoData alloc] init];
    _photoData.paientId = _paientItem.pId;
    _photoData.delegate = self;
    [_photoData reloadDataWithCache:NO];
    
    SDPaientInfoMgr* suffererInfoMgr = [SDPaientInfoMgr shareAGDatabaseManager];
    [suffererInfoMgr creatTable:[SDPhotoInfo class] tableName:kPhotoTableName keyName:nil primaryKey:nil];
    
    
  //  _photoList = [suffererInfoMgr selectALL:[SDPhotoInfo class] tableName:kPhotoTableName];

    _photoList = [suffererInfoMgr select:[SDPhotoInfo class] tableName:kPhotoTableName where:[NSString stringWithFormat:@"patientId = %ld",_photoData.paientId]];
   // _photosDictionay = [[NSMutableDictionary alloc] init];
//    for (SDPhotoInfo* photoInfo in allPhotos) {
//        NSString* dateStr = photoInfo.creationTime;
//        NSMutableArray* tmpArr = [_photosDictionay objectForKey:dateStr];
//        if(nil == tmpArr)
//        {
//            tmpArr = [NSMutableArray arrayWithCapacity:2];
//            [_photosDictionay setObject:tmpArr forKey:dateStr];
//        }
//        [tmpArr addObject:photoInfo];
//    }
//    
//    if(_photosDictionay.count > 0)
//    {
//        _dateArray = [NSMutableArray arrayWithArray:[_photosDictionay allKeys]];
//    }
//    
    [self.collectionView reloadData];
}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (void)showLoading{
    [self finishLoading];
    [VPMBProgressHUD showIndicatorWithText:@"上传中"];
}

- (void)finishLoading
{
    [VPMBProgressHUD hideIndicator];
}

- (void)failedLoading
{
    [self finishLoading];
    [VPMBProgressHUD showAttendAlert:@"上传失败" andIcon:nil];
}

-(UIView*)createHeaderView
{
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeaderViewHeight)];
    headerView.backgroundColor = [UIColor clearColor];
    
    _avatarView = [[SDAvatarView alloc] initWithFrame:CGRectMake(32, 15, kAvatarViewWidth, kAvatarViewHeight)];
    UIImage * defaultImg = [UIImage imageNamed:@"avatar_empty.png"];
    _avatarView.image = defaultImg;
    [headerView addSubview:_avatarView];

    //ID
    _idTextView = [[SDPaientInfoLTView alloc] initWithFrame:CGRectMake(_avatarView.right + 15, _avatarView.top, 170, 30)];
    [_idTextView setName:@"ID"];
    [headerView addSubview:_idTextView];

    //姓名
    _nameTextView = [[SDPaientInfoLTView alloc] initWithFrame:_idTextView.bounds];
    [_nameTextView setName:@"姓名"];
    _nameTextView.top = _idTextView.bottom;
    _nameTextView.left = _idTextView.left;
    [headerView addSubview:_nameTextView];
    
    //性别
    _genderTextView = [[SDPaientInfoLTView alloc] initWithFrame:_idTextView.bounds];
    [_genderTextView setName:@"性别"];
    _genderTextView.top = _nameTextView.bottom;
    _genderTextView.left = _idTextView.left;
    [headerView addSubview:_genderTextView];
    
    //生日
    _birthdayTextView = [[SDPaientInfoLTView alloc] initWithFrame:_idTextView.bounds];
    [_birthdayTextView setName:@"生日"];
    _birthdayTextView.top = _genderTextView.bottom;
    _birthdayTextView.left = _idTextView.left;
    [headerView addSubview:_birthdayTextView];
    
    UIButton* editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage* editImg = [UIImage imageNamed:@"patient_detail_btn_edit.png"];
    [editButton setImage:editImg forState:UIControlStateNormal];
    editButton.frame = CGRectMake(0, _idTextView.top, editImg.size.width, editImg.size.height);
    editButton.right = kScreenWidth - 20;
    [editButton addTarget:self action:@selector(onEditPaientInfo:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:editButton];
    
    return headerView;
}

-(void)refreshProfileInfoView{
    if (CHECK_VALID_STRING(_paientItem.avatar)) {
        NSString* directory = [SDFile getDirectoryInCacheWithName:kAvatarDirectoryName];
        NSString *filePath = [directory stringByAppendingPathComponent:_paientItem.avatar];
        if ([SDFile fileExist:filePath]) {
            _avatarView.image = [_avatarView modifiedImageWithImage:[UIImage imageWithContentsOfFile:filePath]];
        }
        else
        {
            [_avatarView setImageWithURL:nil];
        }
    } else {
        UIImage * defaultImg = [UIImage imageNamed:@"avatar_empty.png"];
        _avatarView.image = defaultImg;
    }
//    if (_avatarView != nil) {
//        [_avatarView setImageWithURL:_paientItem.avatar];
//    }
    
    if (_idTextView != nil && CHECK_VALID_STRING(_paientItem.cId)) {
        _idTextView.valueLabel.text = _paientItem.cId;
    }
    
    if (_nameTextView != nil) {
        _nameTextView.valueLabel.text = _paientItem.name;
    }
    
    if (_genderTextView != nil) {
        _genderTextView.valueLabel.text = [ _paientItem.gender isEqualToString:@"1"] ? @"男" : @"女";
    }
    
    if (_birthdayTextView != nil) {
        _birthdayTextView.valueLabel.text = [SDNSString getTimeStringFromDateString:_paientItem.dateOfBirth formatterString:@"yyyy-MM-dd"];
    }
}

#pragma mark UI Event
-(void)onEditPaientInfo:(id)sender{
    SDPaientEditorViewController* editorViewController = [[SDPaientEditorViewController alloc] init];
    editorViewController.paientItem = _paientItem;
    editorViewController.editable = YES;
    SDNavigationController* navigationCtrl = [[SDNavigationController alloc] initWithRootViewController:editorViewController];
    [self presentViewController:navigationCtrl animated:YES completion:nil];
}

- (void)onBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)onCancel:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onSelectBtnClicked:(id)sender
{
    SDTabBarController* tabBarCtrl = [[SDWindowManager defaultManager] getTabBarController];
    UIView* bottomBar = [tabBarCtrl.myTabBar viewWithTag:10001];
    if (bottomBar == nil) {
        bottomBar = [self bottomBar];
        [tabBarCtrl.myTabBar addSubview:bottomBar];
        bottomBar.tag = 10001;
    }
    _editable = !_editable;
    if (_editable) {
        bottomBar.hidden = NO;
        [ self.navBar.editBtn setTitle:@"取消" forState:UIControlStateNormal];
        
        if (CHECK_VALID_ARRAY(_selectedItemsArray)) {
            [_selectedItemsArray removeAllObjects];
        }
    } else {
        bottomBar.hidden = YES;
        [ self.navBar.editBtn setTitle:@"选择" forState:UIControlStateNormal];
    }
    [self.collectionView reloadData];
}



#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return CHECK_VALID_ARRAY(_photoList) ? _photoList.count : 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    
    SDPhotoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellIdentifier forIndexPath:indexPath];
    [cell setEditable:_editable];
    SDPhotoInfo* photoInfo = _photoList[row];
    [cell setData:photoInfo];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        reusableview.backgroundColor = [UIColor clearColor];
        UIView* headerView  = [reusableview viewWithTag:1001];
        if (!headerView) {
            headerView = [self createHeaderView];
            [self refreshProfileInfoView];
            reusableview.bounds = headerView.bounds;
            headerView.tag = 1001;
            [reusableview addSubview:headerView];
        }
    }
    
    return reusableview;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
  //  NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (CHECK_VALID_ARRAY(_photoList)) {
        SDPhotoInfo* photoInfo = _photoList[row];
        SDPhotoDetailInfoViewController* detailInfoViewCtrl = [[SDPhotoDetailInfoViewController alloc] init];
        detailInfoViewCtrl.photoInfo = photoInfo;
        detailInfoViewCtrl.patientId = _paientItem.pId;
        [self.navigationController pushViewController:detailInfoViewCtrl animated:YES];
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(_photoViewWidth, _photoViewWidth);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.0;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    //float width = collectionView.frame.size.width;
    float width = kScreenWidth;
    float spacing = [self collectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
    int numberOfCells = (width + spacing) / (_photoViewWidth + spacing);
    int inset = (width + spacing - numberOfCells * (_photoViewWidth + spacing) ) / 2;
    
    return UIEdgeInsetsMake(0, inset, 0, inset);
}

#pragma mark - VPTabBarDelegate
-(void) selectBarBtnAtIndex:(NSInteger) index
{
    VPTBarBtn* tabBarItem = [_bottomBar.btnList objectAtIndex:index];
    [tabBarItem setIsSelectedMine:NO];
    __block BOOL flag = NO;
    if (index == 0) {
        [self showLoading];
        for (SDPhotoInfo* photoInfo in _selectedItemsArray) {
            NSString* directory = [SDFile getDirectoryInCacheWithName:kPhotoDiretoryName];
            NSString *filePath = [directory stringByAppendingPathComponent:photoInfo.originalFileName];
            if ([SDFile fileExist:filePath]) {
                UIImage* image = [UIImage imageWithContentsOfFile:filePath];
                [[AliyunOSSManager sharedInstance] uploadObjectSyncWithFileName:photoInfo.originalFileName image:image completion:^(id data, NSError *error) {
                    if (!error) {
                        photoInfo.photoUrl = data;
                        BOOL isSuccess = [[SDPaientInfoMgr shareAGDatabaseManager] update:photoInfo tableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",photoInfo.id]];
                        if (isSuccess) {
                            flag = YES;
                            [self finishLoading];
                        } else {
                            [self failedLoading];
                        }
                    }else{
                        [self failedLoading];
                    }
                }];
                
            }
        }
        
        
    } else if (index == 1){
        
        [_selectedItemsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SDPhotoInfo* photoInfo = (SDPhotoInfo*)obj;
            BOOL isSuccess = [[SDPaientInfoMgr shareAGDatabaseManager] deleteTableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",photoInfo.id]];
            if (isSuccess) {
                [_selectedItemsArray removeObject:photoInfo];
                flag = YES;
            } else {
                
            }
        }];
    }
    
    if (flag) {
        [self initData];
    }
}

#pragma mark -SDBaseDataDelegate
- (void)dataWillStartLoad:(SDBaseData*)model
{
    
}

- (void)data:(SDBaseData*)model didFinishLoadWithError:(NSError*)error nextDataType:(SDBaseDataType)nextDataType
{
    if (!error) {
        if ([model isKindOfClass:[SDPaientPhotoData class]]) {
            SDPaientInfoMgr* dataBaseMgr = [SDPaientInfoMgr shareAGDatabaseManager];
//            for (SDPhotoInfo* infoItem in _photoData.photoList) {
//                NSArray* paientList = [dataBaseMgr select:[SDPaientInfoItem class] tableName:kPaientTableName where:[NSString stringWithFormat:@"pId = %ld",infoItem.pId]];
//                if (!CHECK_VALID_ARRAY(paientList)) {
//                    BOOL success = [dataBaseMgr insert:infoItem tableName:kPaientTableName];
//                    if (success) {
//                        // NSLog(@"inset paient item to local database from backend........");
//                    }
//                }
//            }
//            [self loadData];
            
            _photoList = (NSMutableArray*)_photoData.photoList;
            [self.collectionView reloadData];
        }
    } else {
        
    }
}

@end
